<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>欢迎登录</h2>
        <p>请输入您的账号信息</p>
      </div>

      <div class="auth-form">
        <div class="form-item">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            @keyup.enter="handleLogin"
          />
        </div>

        <div class="form-item">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </div>

        <div class="remember-forgot">
          <div class="remember-me">
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          </div>
          <span class="forgot-password" @click="handleForgotPassword">忘记密码？</span>
        </div>

        <el-button
          type="primary"
          size="large"
          class="submit-btn"
          :loading="loading"
          @click="handleLogin"
        >
          {{ loading ? '登录中...' : '登录' }}
        </el-button>

        <div class="auth-switch">
          还没有账号？
          <span class="switch-link" @click="goToRegister">立即注册</span>
        </div>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading" color="#409eff" :size="32">
        <Loading />
      </el-icon>
    </div>

    <!-- 消息提示容器 -->
    <div class="message-box"></div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user.js'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证
const validateLogin = () => {
  const errors = []
  
  if (!loginForm.username.trim()) {
    errors.push('请输入用户名')
  }
  
  if (!loginForm.password) {
    errors.push('请输入密码')
  } else if (loginForm.password.length < 6) {
    errors.push('密码长度不能少于6位')
  }
  
  return errors
}

// 处理登录
const handleLogin = async () => {
  const errors = validateLogin()
  
  if (errors.length > 0) {
    ElMessage.error(errors[0])
    return
  }

  loading.value = true

  try {
    // 使用用户状态管理登录
    const result = await userStore.login(loginForm.username, loginForm.password)
    
    if (result.success) {
      ElMessage.success('登录成功！')
      
      // 记住我功能
      if (loginForm.remember) {
        localStorage.setItem('rememberedUser', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUser')
      }
      
      // 跳转到首页
      setTimeout(() => {
        router.push('/')
      }, 1000)
    } else {
      ElMessage.error(result.error || '登录失败')
    }
  } catch (error) {
    console.error('登录异常:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessageBox.prompt('请输入您的邮箱地址，我们将发送重置密码链接', '忘记密码', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    inputErrorMessage: '请输入有效的邮箱地址'
  }).then(({ value }) => {
    ElMessage.success(`重置密码链接已发送至: ${value}`)
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 页面加载时检查是否有记住的用户名
const checkRememberedUser = () => {
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    loginForm.username = rememberedUser
    loginForm.remember = true
  }
}

// 初始化
checkRememberedUser()
</script>

<style scoped lang="scss">
// 导入全局样式
@use '../assets/styles/main.scss';

// 登录页面特定样式
.auth-container {
  .auth-card {
    .auth-header {
      h2 {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
    }
  }
}
</style>
